package com.lingo.ffmpegdemo.screen.demo;


import com.spicdt.iot.api.entity.FileUploadFile;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.RandomAccessFile;

@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    private int byteRead;
    private volatile int start = 0; //开始位置
    private static final String file_path = "D:\\Download\\";

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("已连接到服务器");
    }


    @Override
    public void channelRead(ChannelHandlerContext cxt,Object msg) throws Exception {
        if (msg instanceof FileUploadFile){
            log.info("接收到服务端的FileUploadFile对象");
            FileUploadFile fileUploadFile = (FileUploadFile) msg;
            byte[] body = fileUploadFile.getBody(); //文件内容转换为字节流
            byteRead = fileUploadFile.getEndPos(); //获取文件上次读取的位置
            String file_name = fileUploadFile.getFileName();//获取文件名称
            String path = file_path+file_name; //文件路径
            File file = new File(path);//根据文件路径创建文件
            RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");//读写操作，如果文件不存在，则自动创建文件
            randomAccessFile.seek(start); //移动至start位置开始写入文件
            randomAccessFile.write(body);
            start+=byteRead;
            cxt.writeAndFlush(start);//向服务端发送数据，下次开始的位置
            log.info("写入完毕，文件路径为：{}",path);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

}

